package org.changchen.fgt.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.changchen.fgt.config.SourceApiConfig;
import org.changchen.fgt.dto.ApiInfo;
import org.changchen.fgt.dto.VideoDetail;
import org.changchen.fgt.dto.VideoDetailJson;
import org.changchen.fgt.dto.VideoInfo;
import org.changchen.fgt.dto.VideoInfoJson;
import org.changchen.fgt.dto.VideoPlayInfo;
import org.changchen.fgt.service.SourceParseService;
import org.changchen.fgt.service.SourceRequestService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SourceParseServiceImpl implements SourceParseService{
	
	
	private static final String SPLIT_PATTERN = "\\$\\$\\$";
	
	
	@Resource
	private SourceRequestService sourceRequestService;
	
	
	@Override
	public List<VideoInfo> getVideoListFromXml(String url, String word){
		
		try {
			JSONObject jsonRs = sourceRequestService.getList(url, SourceApiConfig.DATA_TYPE_XML, null, null, word, null);
			
			// 处理单条查询结果问题
			String sourceJson = jsonRs.getJSONObject("list").getString("video");
			if(StringUtils.isEmpty(sourceJson)) {
				return Collections.emptyList();
			}
			
			if(sourceJson.indexOf("[") != 0) {
				sourceJson = String.format("[%s]", sourceJson);
			}
			
			List<VideoInfo> videoList = JSON.parseArray(sourceJson, VideoInfo.class);	
			return videoList;
		} catch (Exception e) {
			log.error("请求{}\n出错啦，请稍后再试, {}", url, e);
		}
		
		return Collections.emptyList();
	}
	
	
	
	@Override
	public VideoDetail getVideoDetailFromXml(String code, Integer vodId) {
		
		ApiInfo apiInfo = SourceApiConfig.SRC_CONFIG.get(code);
		
		try {
			
			JSONObject jsonObject = sourceRequestService.getDetail(apiInfo.getUrl(), apiInfo.getDataType(), null, null, vodId.toString(), null);
			VideoDetail detail = JSON.parseObject(jsonObject.getJSONObject("list").getString("video"), VideoDetail.class);
			
			// 播放地址解析
			List<VideoPlayInfo> playSources = this.parsePlaySource(detail, true);
			detail.setPlayList(playSources);
			
			return detail;
			
		} catch (Exception e) {
			log.error("请求出错啦，请稍后再试, {}", e);
		}
		
		return new VideoDetail();
	}
	
	
	@Override
	public List<VideoInfo> getVideoListFromJson(String url, String word){
		
		try {
			JSONObject jsonRs = sourceRequestService.getList(url, SourceApiConfig.DATA_TYPE_JSON, null, null, word, null);
			
			// 处理单条查询结果问题
			JSONArray sourceArray = jsonRs.getJSONArray("list");
			if(CollectionUtils.isEmpty(sourceArray)) {
				return Collections.emptyList();
			}
			
			List<VideoInfoJson> videoList = JSON.parseArray(sourceArray.toJSONString(), VideoInfoJson.class);
			
			List<VideoInfo> resultList = new ArrayList<>();
			videoList.forEach(video -> {
				VideoInfo videoInfo = new VideoInfo();
				BeanUtils.copyProperties(video, videoInfo);
				resultList.add(videoInfo);
			});
			
			return resultList;
		} catch (Exception e) {
			log.error("请求{}\n出错啦，请稍后再试, {}", url, e);
		}
		
		return Collections.emptyList();
	}
	
	
	@Override
	public VideoDetail getVideoDetailFromJson(String code, Integer vodId) {
		
		ApiInfo apiInfo = SourceApiConfig.SRC_CONFIG.get(code);
		
		try {
			
			JSONObject jsonObject = sourceRequestService.getDetail(apiInfo.getUrl(), apiInfo.getDataType(), null, null, vodId.toString(), null);
			
			JSONArray jsonArray = jsonObject.getJSONArray("list");
			
			VideoDetailJson detailJson = JSON.parseObject(jsonArray.getString(0), VideoDetailJson.class);
			
			VideoDetail detail = new VideoDetail();
			BeanUtils.copyProperties(detailJson, detail);
			
			// 资源
			detail.setVodPlayFrom(code);
			
			// 播放地址解析
			List<VideoPlayInfo> playSources = this.parsePlaySource(detail, false);
			detail.setPlayList(playSources);
			
			return detail;
			
		} catch (Exception e) {
			log.error("请求出错啦，请稍后再试, {}", e);
		}
		
		return new VideoDetail();
	}	
	
	
	/**   
	 * @Title:      parsePlaySource   
	 * @Description:播放地址解析   
	 * @param:      @param detail
	 * @param:      @return      
	 * @return:     List<VideoSource>      
	 * @throws   
	 */
	private List<VideoPlayInfo> parsePlaySource(VideoDetail detail, Boolean isXml) {
		
		String source = detail.getSource();
		if(!StringUtils.hasLength(source)) {
			log.error("视频：{}，{}暂无资源！", detail.getId(), detail.getName());
			return Collections.emptyList();
		}
		
		String fromsStr = "";
		String fromUrlsStr = "";
		
		// xml
		if(isXml) {
			if(source.indexOf("[") <= 0) {
				source = JSON.parseObject(source).getString("dd");
				if(StringUtils.hasLength(source)) {
					source = "[" + source + "]";
				}
				
			}				
			JSONArray sourceList = JSON.parseArray(source);
			for(int i=0; i<sourceList.size(); i++) {
				JSONObject jsonObject = sourceList.getJSONObject(i);
				fromsStr = concat4Source(fromsStr, jsonObject.getString("@flag"));
				fromUrlsStr = concat4Source(fromUrlsStr, jsonObject.getString("#text"));
			}
		} else {
			fromsStr = detail.getName();
			fromUrlsStr = detail.getSource();
		}
		
		
		
		
		if(!StringUtils.hasLength(fromsStr) || !StringUtils.hasLength(fromUrlsStr)) {
			log.error("视频：{}，{}暂无资源！", detail.getId(), detail.getName());
			return Collections.emptyList();
		}
		
		// String[] froms = fromsStr.split(SPLIT_PATTERN);
		String[] fromUrls = fromUrlsStr.split(SPLIT_PATTERN);
		
		List<VideoPlayInfo> playSources = new ArrayList<>();
		
		for(int i = 0; i < fromUrls.length; i++) {
			if(!StringUtils.hasLength(fromUrls[i])) {
				log.error("id:{},name:{},index:{},解析视频分源出现问题！", detail.getId(), detail.getName(), i);
				continue;
			}
			
			String[] eps = fromUrls[i].split("\\#");
			for(int j=0; j<eps.length; j++) {
				if(!StringUtils.hasLength(eps[j])) {
					log.error("id:{},name:{},index:{},{},解析分集出现问题！", detail.getId(), detail.getName(), j, eps[j]);
					continue;
				}
				
				String[] nameUrl = eps[j].split("\\$");
				
				if(nameUrl.length < 1) {
					log.error("id:{},name:{},index:{},{},解析name$url出现问题！", detail.getId(), detail.getName(), j, nameUrl);
					continue;
				}
				
				String name = null;
				String url = null;
				
				if(nameUrl.length == 1) {
					name = "全集";
					url = nameUrl[0]; 
				} else {
					name = nameUrl[0];
					url = nameUrl[1];
				}

				// StringEscapeUtils.escapeJavaScript()转义目的是防止字符串中出现单引号
				VideoPlayInfo videoSource = new VideoPlayInfo(j, false, removeQuot(name), url);

				
				playSources.add(videoSource);

			}
		}
		
		return playSources;
	}
	
	
	/**  
	 * <p>Title: concat</p>  
	 * <p>Description: 播放源与下载源合并</p>  
	 * @param str1
	 * @param str2
	 * @return  
	 */  
	private String concat4Source(String str1, String str2) {
		
		if(StringUtils.hasLength(str1) && StringUtils.hasLength(str2)) {
			return str1 + "$$$" + str2;
		}
		
		if(StringUtils.hasLength(str1)) {
			return str1;
		}
		
		if(StringUtils.hasLength(str2)) {
			return str2;
		}
		
		return null;
	}
	
	
	/**  
	 * <p>Title: removeQuot</p>  
	 * <p>Description: 移除引号</p>  
	 * @param str
	 * @return  
	 */  
	private String removeQuot(String str) {
		if(str == null) {
			return "";
		}
		str = str.replaceAll("\"", "").replaceAll("'", "");
		
		if(NumberUtil.isInteger(str)) {
			str = String.format("第%s集", str);
		}
		
		return str;
	}
	
	
	
	
	
}
